if(!dojo._hasResource["market.widgets.GenericForm"]){
dojo._hasResource["market.widgets.GenericForm"] = true;
dojo.require("dijit.form.Select");dojo.require("dijit.form.Button");dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.TextBox");dojo.require("dijit.form.Textarea");
require(["dojo/_base/declare","dijit/_Widget","dojo/html","dojo/dom-attr","dojo/io/iframe"],function(declare,_Widget,html,domAttr,iframe){
declare("market.widgets.GenericForm",[_Widget],{
fieldsetTempl:'<fieldset class="fieldsCollection"><legend>{title}</legend><div class="dotline"></div>{components}</fieldset>',
rowTempl:'<div class="divRow"><label for="{name}" class="label">{label}</label>{component}<span id="{formId}_{name}.error" class="elementError"/></div>',
buttonFormTempl:'<fieldset class="fieldsCollection"><div class="inputButton">{components}</div></fieldset>',
inputTempl:'<input type="{controlType}" id="{name}" name="{name}" value="{value}" {styleDisable} {dojoType}/>',
fileTempl:'<input type="file" name="{name}" value="{value}" size="10" {styleDisable}/>{tooltip}',
textAreaTempl:'<textarea id="{name}" name="{name}" {styleDisable} dojoType="dijit.form.Textarea" style="width:200px">{value}</textarea>',
selectTempl:'<select dojoType="dijit.form.Select" id="{name}" name="{name}" {styleDisable} style="width:200px">{options}</select>',
formTempl:'<div><form id="{formId}" name="{formName}" action="{actionUrl}" method="POST" {enctypeAtt}>{components}</form></div>',
actionUrl:'',formName:'',formId:'',title:'',enctype:'',form:null,handleEvents:null,hasCache:false,ajaxCallUrl:'',ajaxCallType:'',
_multiFiles:null,postCreatedFunc:null,contentId:'',widgetId:'',
constructor:function(args){
   this.contentId = args.contentId;
   this.widgetId = args.id;
},
setDataForm:function(args){
   var _args = (args==null)?{}:args;
   this.dataCreatedForm = args;
   this.title = _args.title ? _args.title:"";
   this.form = _args.form ? _args.form : {};
   this.actionUrl = this.form.actionUrl ? this.form.actionUrl:"";
   this.formName = this.form.formName ? this.form.formName:"";
   this.formId = this.widgetId + "_" + this.formName;
   this.hasCache = _args.hasCache;
   this.enctype = (this.form.enctype == '' || this.form.enctype == null)?'':'enctype="' + this.form.enctype + '"';
   this._multiFiles = null;
},
removeComponents:function (){
   fields = this.form.fields == null ? [] : this.form.fields;
   fields = this.form.buttons == null ? fields : fields.concat(this.form.buttons);
   if (fields != null){
      for (var index=0; index<fields.length; index++){
         dijit.registry.remove(fields[index].name);
      }
   }
},
getFormToObject:function(){
   return dojo.formToObject(this.formId);
},
createForm:function(){
   var commonForm = this;
   var createdFormDataSource = null;
   var cacheWidget = SYSTEMWIDGET.cacheWidget();
   if (this.hasCache && cacheWidget.containKey(this.ajaxCallUrl)){
      createdFormDataSource = cacheWidget.getValue(this.ajaxCallUrl);
   }
   if (createdFormDataSource == null){
      var args = {
         ajaxUrl: this.ajaxCallUrl,
         contentId: this.contentId,
         callback: function (data){
            SYSTEMWIDGET.cacheWidget().addItem(commonForm.ajaxCallUrl, data);
            commonForm.setDataForm(data);
            commonForm.show();
      }};
      SYSTEMWIDGET.callAjaxWidget(args, this.ajaxCallType);
   }else {
      commonForm.setDataForm(createdFormDataSource);
      commonForm.show();
   }
},
createFormFormDataSource:function(dataSource){
   this.setDataForm(dataSource);
   this.show();
},
show:function(){
   this.removeComponents();
   var htmlData = this._genericForm();
   console.log('ContentId: ' + this.contentId + " ---- WidgetId: " + this.widgetId);
   html.set(dojo.byId(this.contentId), htmlData, {parseContent: true});
   this._connectEvents();
   this._postCreated();
},
callSaveForm:function(callBack){
   var localForm = this;
   var callbackFunction = function(data, msg) {
     if (localForm._hasError(data) && callBack.handleError == null) localForm._showError(data);
     else if (localForm._hasError(data) && callBack.handleError != null) callBack.handleError(data);
     else callBack.handleSuccess(data);
   };
   if (this.enctype == 'enctype="multipart/form-data"'){
      if (this._multiFiles != null){
         this._uploadFiles(callBack);
      }else {
         iframe.send({form:localForm.formId,handleAs:'json',load:callbackFunction,
            error: function(type, err) {
                window.alert(err.message);
            }
        });
      }
   }else {
       var args ={form:this.formId,callback: callbackFunction};
       SYSTEMWIDGET.ajaxWidget(args, this.contentId).callXhrPostForm();
   }
},
_postCreated:function(){
   if (this.postCreatedFunc != null) this.postCreatedFunc(this);
},
_uploadFiles:function(callBack){
   var localForm = this;
   var currentForm = dojo.byId(this.formId);
   var elements = (currentForm==null)?null:currentForm.elements;
   for (var index=0; index<4; index++){
      var _nextFormId = this.formId+"_"+index;
      var nextFileForm = dojo.byId(_nextFormId);
      var fileComponent = nextFileForm[this._multiFiles.name];
      if (!(fileComponent.value == null || fileComponent.value.length==0)){
         if (elements!=null){
            for (var eIndex=0;eIndex<elements.length;eIndex++){
               var element = elements[eIndex];
               var _fileInput = document.createElement('input'); 
               domAttr.set(_fileInput,{name:element.name,type:"hidden",value:element.value});
               nextFileForm.appendChild(_fileInput);
            }
         };
         var _aynsFunction=function(uploadForm,uploadCompoment){
            var _loadFunc=function(data){
               if (localForm._hasError(data)){
                  localForm._showError(data,uploadForm);
               }else {
                  uploadCompoment.style.display = 'none';
                  callBack.handleSuccess(data);
               }
            };
            iframe.send({form:_nextFormId,handleAs:'json',load:_loadFunc,error: function(type, err) {
               window.alert(err.message);
            }});
         };
         _aynsFunction(_nextFormId,fileComponent);
      }
   }
},
_hasError:function(errorData){
   var hasError = errorData.hasError;
   if (hasError == true) return true;
   return false;
},
_showError:function(errorData,uploadForm){
   var fields = (errorData.fields==null)?[]:errorData.fields;
   for (var index=0; index<fields.length; index++){
      fieldObject=fields[index];
      var control=dojo.byId(this.formId+'_'+fieldObject.name + '.error');
      if (control==null)
         control=dojo.byId(uploadForm+'_'+fieldObject.name + '.error');
      else 
         control.innerHTML = fieldObject.value;
   }
},
_connectEvents:function(){
   var localwidgetId = this.widgetId;
   var genericForm = this;
   if (this.handleEvents.click != null){
      var clickEvents = this.handleEvents.click.events;
      for(var index=0; index<clickEvents.length; index++){
         dojo.query('#'+this.contentId+' [id="'+clickEvents[index]+'"]').onclick(function(){
            var eventName = localwidgetId+"_"+this.id+'Click';
            console.log('Click Event: ' + eventName);
            genericForm.handleEvents.click[this.id]();
         });
      }
   }
},
_genericForm:function(){
   var fields=this.form.fields;
   var htmlData='';
   var htmlGroup='';
   var controlHTML='';
   var multifileHTML='';
   var lastTitle=this.title;
   if (fields != null){
      for (var index=0; index<fields.length; index++){
         var control = fields[index];
         var controlName = control.name;
         var controlType = control.type;
         control.value = (control.value==null)?'':control.value;
         control.styleDisable = control.disable=="true"?"readonly=true":"";
         if (controlName == "layout" && controlType == "group"){
            if (index>0){
               if(this._multiFiles == null){
                  htmlGroup += dojo.replace(this.fieldsetTempl, {title: lastTitle, components:controlHTML});
               }else{
                  multifileHTML = dojo.replace(this.fieldsetTempl, {title: lastTitle, components:multifileHTML});
               }
            }
            controlHTML = '';
            lastTitle = control.title;
            continue;
         }
         switch (controlType){
         case "hidden":
            controlHTML += this._parseHiddenHtml(control.name, control.value, control.styleDisable);
            break;
         case "text":
         case "0":
            controlHTML += this._parseInputHtml(control, 'text', 'dojoType="dijit.form.TextBox"');
            break;
         case "number":
         case "1":
         case "2":
            controlHTML += this._parseInputHtml(control, 'text', 'dojoType="dijit.form.NumberTextBox" constraints="{pattern:\'###0\'}"');
            break;
         case "longText":
            controlHTML += this._parseComponentHtml(control, 'textarea', 'dojoType="dijit.form.Textarea"', this.textAreaTempl);
            break;
         case "multiText":
            controlHTML += this._parseSelectedHtml(control, 'select', 'dojoType="dijit.form.Select"', control.datasource);
            break;
         case "date":
         case "3":
            controlHTML += this._parseInputHtml(control, 'text', 'dojoType="opm.widgets.CustomDateTextBox"');
            break;
         case "boolean":
         case "4":
            controlHTML += this._parseInputHtml(control, 'checkbox', 'dojoType="dijit.form.CheckBox"');
            break;
         case "singleFile":
            controlHTML += this._parseInputHtml(control, 'file', '');
            break;
         case "multipleFile":
            multifileHTML += this._parseMultiFilesHtml(control);
            this._multiFiles = control;
            break;
         case "password":
            controlHTML += this._parseInputHtml(control, 'password', 'dojoType="dijit.form.TextBox"');
            break;
         }
      }
      htmlGroup += dojo.replace(this.fieldsetTempl,{title:lastTitle,components:controlHTML});
      var htmlButtons='';
      var buttons=this.form.buttons;
      if (buttons != null){
         for (var index=0; index<buttons.length; index++){
            var button=buttons[index];
            var buttonType = (button.type == null)?"button":button.type;
            htmlButtons += '<input id="'+button.name+'" type="'+buttonType+'" dojoType="dijit.form.Button" label="'+button.label+'"/>'; 
         }
      }
      var formObject={formId:this.formId, formName:this.formName, actionUrl:this.actionUrl, enctypeAtt:this.enctype};
      if (this._multiFiles == null){
         formObject.components = htmlGroup + dojo.replace(this.buttonFormTempl, {components:htmlButtons});
         htmlData = dojo.replace(this.formTempl,formObject);
      }else {
         formObject.components=htmlGroup;
         htmlData = dojo.replace(this.formTempl,formObject) + multifileHTML + dojo.replace(this.buttonFormTempl, {components:htmlButtons});
      }
   }
   return htmlData;
},
_parseMultiFilesHtml:function(control){
   var controlHTML='';
   for (var index=0; index<4; index++){
      control.tooltip='';
      if (control.hasTooltip){
         control.tooltip='<input type="text" name="'+control.tooltipName+'" dojoType="dijit.form.TextBox" />';
      }
      var extFormId = this.formId+"_"+index;
      var contents=this._parseRowHtml(control,'file','',this.fileTempl,extFormId);
      controlHTML+=dojo.replace(this.formTempl,{components:contents,formId:extFormId, formName:this.formName+"_"+index, actionUrl:this.actionUrl, enctypeAtt:this.enctype});
   }
   return controlHTML;
},
_parseHiddenHtml:function(controlName,controlValue,styleDisable){
   var htmlString = '<input type="hidden" id="'+controlName+'" name="'+controlName+'" value="'+controlValue+'" '+styleDisable+'>';
   return htmlString;
},
_parseSelectedHtml:function(control,controlType,dojoType,dataSource){
   var optionHTML = '';
   for (var index=0; index<dataSource.length; index++){
      var option = dataSource[index];
      var optionValue = option.value;
      optionHTML += '<option value="'+optionValue+'" '+((optionValue==controlValue)?'selected':'')+'>'+option.label+'</option>';
   }
   control["options"] = optionHTML;
   htmlString = this._parseComponentHtml(control,controlType,dojoType,this.selectTempl);
   return htmlString;
},
_parseInputHtml:function(control,controlType,dojoType){
   htmlString = this._parseComponentHtml(control,controlType,dojoType,this.inputTempl);
   return htmlString;
},
_parseComponentHtml:function(control,controlType,dojoType,templateHTML){
   return this._parseRowHtml(control,controlType,dojoType,templateHTML,this.formId);
},
_parseRowHtml:function(control,controlType,dojoType,templateHTML,formId){
   control["controlType"]=controlType;
   control["dojoType"]=dojoType;
   htmlString=dojo.replace(this.rowTempl,{formId:formId,name:control.name,label:control.label,component:dojo.replace(templateHTML, control)});
   return htmlString;
}
});});}
